﻿/*
Copyright © Naveen Hegde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Neither the name of the author, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior written 
permission. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace NvinInstaller
{
    public partial class ProjectPropertiesControl : UserControl
    {
        ProjectProperties properties = ApplicationManager.GetApplicationManager().Properties;        

        public ProjectPropertiesControl()
        {
            InitializeComponent();
        }

        private void skinRadioButtonComplete_CheckedChanged(object sender, EventArgs e)
        {
            if (skinRadioButtonComplete.Checked)
            {
                properties.UserInterfaceType = UIType.Complete;
            }
        }

        private void skinRadioButtonFeatureTree_CheckedChanged(object sender, EventArgs e)
        {
            if (skinRadioButtonFeatureTree.Checked)
            {
                properties.UserInterfaceType = UIType.FeatureTree;
            }
        }

        private void skinRadioButtonInstallDir_CheckedChanged(object sender, EventArgs e)
        {
            if (skinRadioButtonInstallDir.Checked)
            {
                properties.UserInterfaceType = UIType.InstallDirectory;
            }
        }

        private void skinRadioButtonMinimal_CheckedChanged(object sender, EventArgs e)
        {
            if (skinRadioButtonMinimal.Checked)
            {
                properties.UserInterfaceType = UIType.Minimal;
            }
        }

        private void ProjectPropertiesControl_Load(object sender, EventArgs e)
        {
            // Load control
            textBoxProductName.Text = properties.ProductName;
            textBoxManufacturer.Text = properties.Manufacturer;
            textBoxDescription.Text = properties.Description;
            textBoxComments.Text = properties.Comments;
            textBoxVersion.Text = properties.Version;
            textBoxLicense.Text = properties.LicenseFile;
            textBoxOutput.Text = properties.OutputFile;

            switch (properties.UserInterfaceType)
            {
                case UIType.Complete:
                    skinRadioButtonComplete.Checked = true;
                    break;
                case UIType.FeatureTree:
                    skinRadioButtonFeatureTree.Checked = true;
                    break;
                case UIType.InstallDirectory:
                    skinRadioButtonInstallDir.Checked = true;
                    break;
                case UIType.Minimal:
                    skinRadioButtonMinimal.Checked = true;
                    break;
            }
        }

        private void skinButtonBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = false;
            dlg.Filter = "RTF files|*.rtf";
            dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                textBoxLicense.Text = dlg.FileName;
            }
        }

        private void skinButtonOutput_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            dlg.Filter = "MSI files|*.msi";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                textBoxOutput.Text = dlg.FileName;
            }
        }

        private void addChildToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeViewFeature.Nodes.Count == 0)
            {
                properties.Features.Add(new Feature("New Feature0"));
                TreeNode newNode = treeViewFeature.Nodes.Add("New Feature0");
                return;
            }
            for (int i = 0; i < treeViewFeature.Nodes.Count; i++)
            {
                bool found = false;
                for (int j = 0; j < treeViewFeature.Nodes.Count; j++)
                {
                    if (treeViewFeature.Nodes[j].Text.Equals("New Feature" + i,StringComparison.OrdinalIgnoreCase))
                    {
                        found = true;
                    }
                }
                if (found == false)
                {
                    properties.Features.Add(new Feature("New Feature" + i));
                    TreeNode newNode = treeViewFeature.Nodes.Add("New Feature" + i);
                    return;
                }
            }
            properties.Features.Add(new Feature("New Feature" + treeViewFeature.Nodes.Count));
            treeViewFeature.Nodes.Add("New Feature" + treeViewFeature.Nodes.Count);
        }

        private void deleteChildToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (treeViewFeature.SelectedNode.Parent != null)
            //{
                foreach (Feature value in properties.Features)
                {
                    if (IsUsed(value) == false && value.Name.Equals(treeViewFeature.SelectedNode.Text, StringComparison.OrdinalIgnoreCase))
                    {
                        properties.Features.Remove(value);
                        treeViewFeature.SelectedNode.Remove();
                        break;
                    }
                }
            //}
        }

        private bool IsUsed(Feature value)
        {
            return false;
        }

        private void renameChildToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeViewFeature.SelectedNode.BeginEdit();
        }

        private void expandToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeViewFeature.SelectedNode.Expand();
        }

        private void collapseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeViewFeature.SelectedNode.Collapse();
        }

        private void treeViewFeature_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            treeViewFeature.SelectedNode = e.Node;
            e.Node.ContextMenuStrip = contextMenuStrip;
        }

        public void Reload()
        {
            if (ApplicationManager.GetApplicationManager().FeatureTree != null)
            {
                panelFeature.Controls.Remove(treeViewFeature);
                treeViewFeature = ApplicationManager.GetApplicationManager().FeatureTree;
                treeViewFeature.ContextMenuStrip = contextMenuStrip;
                treeViewFeature.Dock = DockStyle.Fill;
                treeViewFeature.ImageList = imageList;
                treeViewFeature.LabelEdit = true;
                treeViewFeature.AfterLabelEdit += new System.Windows.Forms.NodeLabelEditEventHandler(this.treeViewFeature_AfterLabelEdit);
                treeViewFeature.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.treeViewFeature_NodeMouseClick);
                panelFeature.Controls.Add(treeViewFeature);
            }

            OnLoad(null);
        }

        public void Unload()
        {
            treeViewFeature.AfterLabelEdit -= new System.Windows.Forms.NodeLabelEditEventHandler(this.treeViewFeature_AfterLabelEdit);
            if (ApplicationManager.GetApplicationManager().FeatureTree == null)
            {
                ApplicationManager.GetApplicationManager().FeatureTree = treeViewFeature;
            }            
        }

        private void textBoxDescription_TextChanged(object sender, EventArgs e)
        {
            properties.Description = textBoxDescription.Text;
        }

        private void textBoxComments_TextChanged(object sender, EventArgs e)
        {
            properties.Comments = textBoxComments.Text;
        }

        private void textBoxLicense_TextChanged(object sender, EventArgs e)
        {
            properties.LicenseFile = textBoxLicense.Text;
        }

        private void textBoxOutput_TextChanged(object sender, EventArgs e)
        {
            properties.OutputFile = textBoxOutput.Text;
        }

        private void treeViewFeature_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            string label = string.Empty;
            if (e.Label == null)
                label = e.Node.Text;
            else
                label = e.Label;
            try
            {
                foreach (Feature feature in properties.Features)
                {
                    if (feature.Name.Equals(label, StringComparison.OrdinalIgnoreCase))
                    {
                        e.CancelEdit = true;
                        return;
                    }
                }
                properties.Features.Clear();
                foreach (TreeNode node in treeViewFeature.Nodes)
                {
                    if (node != e.Node)
                    {
                        properties.Features.Add(new Feature(node.Text));
                    }
                    else
                    {
                        properties.Features.Add(new Feature(label));
                    }
                }
            }
            catch
            {
            }
        }

        private void textBoxProductName_Validated(object sender, EventArgs e)
        {
            string text = textBoxProductName.Text;
            if (ValidateText(text))
            {
                properties.ProductName = text;
                errorProvider.SetError(this.textBoxProductName, "");
            }
            else
            {
                errorProvider.SetError(this.textBoxProductName, "Please enter only alphabetic characters or '_'");
            }
        }

        private void textBoxManufacturer_Validated(object sender, EventArgs e)
        {
            string text = textBoxManufacturer.Text;
            if (ValidateText(text))
            {
                properties.Manufacturer = text;
                errorProvider.SetError(this.textBoxManufacturer, "");
            }
            else
            {
                errorProvider.SetError(this.textBoxManufacturer, "Please enter only alphabetic characters or '_'");
            }
        }

        private void textBoxVersion_Validated(object sender, EventArgs e)
        {
            if (Validateversion(textBoxVersion.Text))
            {
                properties.Version = textBoxVersion.Text;
                errorProvider.SetError(this.textBoxVersion, "");
            }
            else
            {
                errorProvider.SetError(this.textBoxVersion, "Please enter only alphabetic characters or '_'");
            }
        }

        private bool Validateversion(string p)
        {
            string[] version = p.Split(".".ToCharArray());
            if (version.Length == 0 || version.Length > 4)
            {
                return false;
            }
            foreach (string val in version)
            {
                uint number;
                if (uint.TryParse(val, out number) == false)
                {
                    return false;
                }
            }
            return true;
        }

        private bool ValidateText(string text)
        {
            foreach (char c in text)
            {
                if (Char.IsLetter(c) == false && c != '_')
                {
                    return false;
                }
            }
            return true;
        }
    }
}
